package com.lsk.admin.AdminSystem;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.util.DateUtil;
import com.lsk.util.MD5;
import com.lsk.util.PageUtil;
import com.lsk.util.ReturnData;
import com.lsk.util.Syslog;
import com.lsk.util.UtilUUID;
import com.lsk.util.UuidUtil;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class AdminSystemService {
    Cache cache = Redis.use("ACTIVITYUSER");

    public ReturnData saveRule(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        try {
            String rules = ((String[])map.get("rules"))[0];
            String name = ((String[])map.get("name"))[0];
            String parentid = ((String[])map.get("parentid"))[0];
            Record record = new Record();
            record.set("name", name).set("type", "button");
            record.set("url", rules).set("percode", rules);
            if (!"".equals(parentid))
                record.set("parentid", Integer.valueOf(Integer.parseInt(parentid)));
            boolean result = Db.save("sys_permission", record);
            if (result) {
                returnData.setCode("000000");
                returnData.setMsg("添加成功");
            } else {
                returnData.setCode("111111");
                returnData.setMsg("添加失败");
            }
        } catch (Exception e) {
            returnData.setCode("111111");
            returnData.setMsg("添加异常" + e);
            Syslog.error("添加权限异常"+ e);
        }
        return returnData;
    }

    public ReturnData savePermissionService(String id, String parentid, String url, String name) {
        boolean sa = false;
        if ("".equals(id) || id == null) {
            Record record = (new Record()).set("id", UtilUUID.getUUID()).set("url", url).set("name", name).set("type", "menu");
            if (!"".equals(parentid))
                record.set("parentid", parentid);
            sa = Db.save("sys_permission", "id", record);
        } else {
            Record record = (new Record()).set("url", url).set("name", name).set("type", "menu").set("id", id);
            if (!"".equals(parentid))
                record.set("parentid", parentid);
            sa = Db.update("sys_permission", "id", record);
        }
        ReturnData returnData = new ReturnData();
        returnData.setCode(String.valueOf(sa));
        return returnData;
    }

    public ReturnData ruleList(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String type = ((String[])map.get("type"))[0];
        String url = ((String[])map.get("url"))[0];
        String name = ((String[])map.get("name"))[0];
        int curr = Integer.parseInt(((String[])map.get("currentPage"))[0]);
        int size = Integer.parseInt(((String[])map.get("limit"))[0]);
        String sql = "SELECT *from sys_permission where 1=1 ";
        if (!"".equals(type)) {
            sql = sql + " and parentId ='" + type + "'";
        } else {
            sql = sql + " and  parentid ='0'";
        }
        if (!"".equals(url))
            sql = sql + " and url like '%" + url + "%'";
        if (!"".equals(name))
            sql = sql + " and name like '%" + name + "%'";
        PageUtil<List<Record>> pageUtil = new PageUtil(curr, size, sql);
        returnData.setData(pageUtil);
        return returnData;
    }

    public ReturnData topMenu() {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT *from sys_permission WHERE parentid ='0' ";
        List<Record> list = Db.find(sql);
        returnData.setData(list);
        return returnData;
    }

    public ReturnData topDepartment() {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT *from sys_department where parentDepartmentId is null or parentDepartmentId=''";
        List<Record> list = Db.find(sql);
        returnData.setData(list);
        return returnData;
    }

    public ReturnData department() {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT *from sys_department ";
        List<Record> list = Db.find(sql);
        returnData.setData(list);
        return returnData;
    }

    public ReturnData saveDepartment(String id, String name, String userId) {
        ReturnData returnData = new ReturnData();
        boolean sa = false;
        if ("".equals(id) || id == null) {
            Record record = (new Record()).set("id", UtilUUID.getUUID()).set("name", name).set("userId", userId);
            sa = Db.save("sys_department", "id", record);
        } else {
            Record record = (new Record()).set("id", id).set("name", name).set("userId", userId);
            sa = Db.update("sys_department", "id", record);
        }
        returnData.setCode(String.valueOf(sa));
        return returnData;
    }

    public ReturnData rpermissionTypeService(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT *from sys_permission_type";
        List<Record> recordList = Db.find(sql);
        if (recordList.size() > 0)
            returnData.setData(recordList);
        return returnData;
    }

    public ReturnData saveRpermissionTypeService(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = ((String[])map.get("id"))[0];
        String name = ((String[])map.get("name"))[0].trim();
        Record record = (new Record()).set("type_name", name);
        boolean re = false;
        if ("".equals(id)) {
            re = Db.save("sys_permission_type", record);
        } else {
            record.set("id", id);
            re = Db.update("sys_permission_type", "id", record);
        }
        returnData.setCode(re + "");
        returnData.setData(record);
        return returnData;
    }

    public ReturnData delRpermissionTypeService(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = ((String[])map.get("id"))[0];
        String sql = "DELETE from sys_permission_type where id='" + id + "'";
        int del = Db.delete(sql);
        returnData.setData(Integer.valueOf(del));
        return returnData;
    }

    public Map departmentRoleListService(String id) {
        String sql = "SELECT\n\tsd.sys_department_id AS id,\n\tsr.`name`\nFROM\n\tsys_department_role sd\nLEFT JOIN sys_role sr ON sd.sys_role_id = sr.`name`\nWHERE\n\tsd.sys_department_id =" + id + "";
        List<Record> list = Db.find(sql);
        Map<Object, Object> map = new HashMap<>();
        map.put("total", Integer.valueOf(list.size()));
        map.put("data", list);
        return map;
    }

    public ReturnData saveAdminService(Map<String, String[]> map, String userId) {
        ReturnData returnData = new ReturnData();
        boolean sa = false;
        String id = ((String[])map.get("id"))[0];
        String userCode = ((String[])map.get("userCode"))[0];
        String userName = ((String[])map.get("userName"))[0];
        String spotName =((String [])map.get("spotName"))[0];
        String password = ((String[])map.get("password"))[0];
        String phone = ((String[])map.get("phone"))[0];
        String type = ((String[])map.get("type"))[0];
        Record userRecord = (Record)this.cache.get(userId);
        String adminUserId = userRecord.getStr("adminUserId");
        adminUserId = (type == "1") ? userRecord.getStr("id") : adminUserId;
        type = "0".equals(userRecord.getStr("type")) ? "1" : "2";
        String salt = UtilUUID.getOrderIdByUUId();
        if ("".equals(id) || "null".equals(id) || "null".equals(id)) {
            Record record = new Record();
            record.set("id", UuidUtil.get32UUID()).set("locked", "0").set("type", type).set("adminUserId", adminUserId);
            record.set("password", MD5.md5(userCode + salt + password))
                    .set("userName", userName).set("salt", salt).set("userCode", userCode).set("spotName",spotName)
                    .set("phone", phone);
            sa = Db.save("sys_user", "id", record);
        } else {
            Record record = (new Record()).set("locked", "0");
            record.set("password", MD5.md5(userCode + salt + password))
                    .set("userName", userName).set("salt", salt).set("userCode", userCode).set("id", id)
                    .set("phone", phone);
            sa = Db.update("sys_user", "id", record);
        }
        returnData.setCode(String.valueOf(sa));
        return returnData;
    }

    public ReturnData getAdmin(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        boolean sa = false;
        String userCode = ((String[])map.get("userCode"))[0];
        String sql = "select id from sys_user where userCode='" + userCode + "'";
        List<Record> recordList = Db.find(sql);
        if (recordList.size() == 0)
            sa = true;
        returnData.setCode(String.valueOf(sa));
        return returnData;
    }

    public ReturnData saveUserPermission(Map<String, String[]> map) {
        ReturnData data = new ReturnData();
        String[] idsChecked = map.get("ids[]");
        String userId = ((String[])map.get("userId"))[0];
        String type = ((String[])map.get("type"))[0];
        List<Record> recordList = new ArrayList<>();
        if ("user".equals(type)) {
            String del = "DELETE from sys_user_permission where sys_user_id='" + userId + "'";
            Db.delete(del);
            if (idsChecked != null) {
                for (int i = 0; i < idsChecked.length; i++) {
                    Record record = (new Record()).set("sys_user_id", userId).set("sys_permission_id", idsChecked[i]);
                    recordList.add(record);
                }
                int[] arrayOfInt = Db.batchSave("sys_user_permission", recordList, recordList.size());
            }
        }
        data.setData("true");
        return data;
    }

    public ReturnData saveAuthorizationButtonService(String id, String name, String url, String parentid) {
        ReturnData returnData = new ReturnData();
        boolean sa = false;
        if ("".equals(id) || id == null || "null".equals(id)) {
            Record record = (new Record()).set("id", UtilUUID.getUUID()).set("name", name).set("url", url).set("parentid", parentid).set("type", "button");
            sa = Db.save("sys_permission", "id", record);
        } else {
            Record record = (new Record()).set("id", id).set("name", name).set("url", url).set("parentid", parentid).set("type", "button");
            sa = Db.update("sys_permission", "id", record);
        }
        returnData.setCode(String.valueOf(sa));
        return returnData;
    }

    public ReturnData findAllResource(String type, String userId) {
        ReturnData data = new ReturnData();
        Map<Object, Object> returnMap = new LinkedHashMap<>();
        try {
            List<Record> record1 = new ArrayList<>();
            Record userRecord = (Record)this.cache.get(userId);
            List<Record> permissionList = (List<Record>)userRecord.get("permission");
            int i;
            for (i = 0; i < permissionList.size(); i++) {
                String parentid = ((Record)permissionList.get(i)).getStr("parentid");
                if (parentid == null || "0".equals(parentid))
                    record1.add(permissionList.get(i));
            }
            permissionList.removeAll(record1);
            for (i = 0; i < record1.size(); i++) {
                List<Record> records = new ArrayList<>();
                records.add(record1.get(i));
                String name = ((Record)record1.get(i)).getStr("name");
                String id = ((Record)record1.get(i)).getStr("id");
                for (int j = 0; j < permissionList.size(); j++) {
                    List<Record> recordList = new ArrayList<>();
                    for (int k = 0; k < permissionList.size(); k++) {
                        String secondId = ((Record)permissionList.get(j)).getStr("id");
                        if (secondId.equals(((Record)permissionList.get(k)).getStr("parentid")))
                            recordList.add(permissionList.get(k));
                    }
                    ((Record)permissionList.get(j)).set("button", recordList);
                    if (id.equals(((Record)permissionList.get(j)).getStr("parentid"))) {
                        ((Record)permissionList.get(j)).set("button", new ArrayList());
                        records.add(permissionList.get(j));
                    }
                }
                returnMap.put(name, records);
            }
            data.setData(returnMap);
        } catch (Exception e) {
            Syslog.error(e);
            Syslog.error("获取权限数据异常"+ e);
        }
        return data;
    }

    public List<Record> adminListService(int currentPage, int size, String userName, String userCode, String type) {
        String sql = "SELECT *from sys_user where   type='" + (Integer.parseInt(type) + 1) + "' ";
        if (!"".equals(userCode) && !"null".equals(userCode) && userCode != null)
            sql = sql + " and userCode like '%" + userCode + "%'";
        if (!"".equals(userName) && !"null".equals(userName) && userName != null)
            sql = sql + " and userName like '%" + userName + "%'";
        PageUtil<Record> pageUtil = new PageUtil(currentPage, size, sql);
        List<Record> list = pageUtil.getList();
        return list;
    }

    public ReturnData buttonAjaxService(String id) {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT *from sys_permission WHERE type='button'  and parentid='" + id + "'";
        List<Record> recordList = Db.find(sql);
        returnData.setData(recordList);
        return returnData;
    }

    public ReturnData addRoleInfo(Map<String, String[]> map, String userId) throws Exception {
        String adminUserId = userId;
        ReturnData data = new ReturnData();
        String name = ((String[])map.get("name"))[0];
        Record record = new Record();
        String roleId = UtilUUID.getUUID();
        record.set("name", name)
                .set("id", roleId)
                .set("available", "1")
                .set("createTime", new Date())
                .set("adminUserId", adminUserId);
        boolean isSuccess = Db.save("sys_role", record);
        Record userRole = (new Record()).set("id", UtilUUID.getUUID()).set("sys_user_id", userId).set("sys_role_id", roleId);
        boolean sa = Db.save("sys_user_role", "id", userRole);
        if (isSuccess && sa) {
            data.setData("true");
        } else {
            data.setData("false");
            throw new Exception();
        }
        return data;
    }

    public ReturnData roleList(Map<String, String[]> map, String userId) {
        ReturnData data = new ReturnData();
        try {
            Record userRecord = (Record)this.cache.get(userId);
            String adminUserId = userRecord.getStr("adminUserId");
            int curr = Integer.parseInt(((String[])map.get("currentPage"))[0]);
            int size = Integer.parseInt(((String[])map.get("size"))[0]);
            String sql = "SELECT a.id, a.`name`, IFNULL(group_concat(c.`name`), '') as permission FROM sys_role a \nLEFT JOIN sys_role_permission b ON a.id = b.sys_role_id\nLEFT JOIN sys_permission c ON b.sys_permission_id = c.id\nWHERE a.adminUserId='" + userId + "'  GROUP BY `name`, id order by a.createTime DESC";
            PageUtil<List<Record>> pageUtil = new PageUtil(curr, size, sql);
            data.setData(pageUtil);
            return data;
        } catch (Exception e) {
            Syslog.error("查询权限异常"+ e);
            return data;
        }
    }

    public ReturnData roleDel(Map<String, String[]> map, String userId) throws Exception {
        ReturnData data = new ReturnData();
        String rid = ((String[])map.get("rid"))[0];
        String sql0 = "DELETE FROM sys_role where id ='" + rid + "'";
        int aa = Db.delete(sql0);
        String sql = "SELECT COUNT(*) as number FROM sys_role_permission a WHERE a.sys_role_id ='" + rid + "'";
        int num = Db.queryInt(sql).intValue();
        String sql2 = "DELETE FROM sys_role_permission WHERE sys_role_id ='" + rid + "'";
        int ss = Db.delete(sql2);
        String sql3 = "DELETE FROM sys_user_role  WHERE sys_user_id='" + userId + "' AND sys_role_id='" + rid + "'";
        int ss2 = Db.delete(sql3);
        if (aa == 1 && num == ss && ss2 == 1) {
            data.setData("success");
        } else {
            data.setData("false");
        }
        return data;
    }

    public ReturnData roleList() {
        ReturnData data = new ReturnData();
        try {
            String sql = "SELECT a.id, a.`name`, IFNULL(group_concat(c.`name`), '') as permission FROM sys_role a \nLEFT JOIN sys_role_permission b ON a.id = b.sys_role_id\nLEFT JOIN sys_permission c ON b.sys_permission_id = c.id\nWHERE 1=1  GROUP BY `name`, id order by a.createTime DESC";
            data.setData(Db.find(sql));
            return data;
        } catch (Exception e) {
            Syslog.error("查询权限异常"+ e);
            return data;
        }
    }

    public List<Record> treePermissionByUserId(String userId) {
        Record record = (Record)this.cache.get(userId);
        List<Record> permission = (List<Record>)record.get("permission");
        List<Record> onePermission = new ArrayList<>();
        List<Record> twoPermission = new ArrayList<>();
        int i;
        for (i = 0; i < permission.size(); i++) {
            Record temp = permission.get(i);
            if (!"0".equals(temp.getStr("parentid"))) {
                twoPermission.add(temp);
            } else {
                onePermission.add(temp);
            }
        }
        for (i = 0; i < onePermission.size(); i++) {
            Record temp = onePermission.get(i);
            String id = temp.getStr("id");
            List<Record> tempTwoList = new ArrayList<>();
            for (int j = 0; j < twoPermission.size(); j++) {
                Record tempTwo = onePermission.get(i);
                if (tempTwo.getStr("parentid") == id)
                    tempTwoList.add(tempTwo);
            }
            temp.set("twoPermission", tempTwoList);
            onePermission.set(i, temp);
        }
        return onePermission;
    }

    public List<Record> getPermissionByUserIdAndPermissionId(String userId, String permissionId) {
        Record record = (Record)this.cache.get(userId);
        List<Record> permission = (List<Record>)record.get("permission");
        List<Record> onePermission = new ArrayList<>();
        for (int i = 0; i < permission.size(); i++) {
            Record temp = permission.get(i);
            if (permissionId.equals(temp.getStr("parentid")))
                onePermission.add(temp);
        }
        return onePermission;
    }

    public List<Record> selectPermissionByRoleId(String roleId) {
        String sql = "SELECT spe.* from sys_permission   spe LEFT JOIN sys_role_permission srp on srp.sys_permission_id=spe.id\nWHERE srp.sys_role_id='" + roleId + "'  GROUP BY spe.id ";
        List<Record> list = Db.find(sql);
        this.cache.setex(roleId + "permission", 1800, list);
        return list;
    }

    public ReturnData settingUserOrRolePerssionService(String id, String type, String primissionId, boolean state) {
        ReturnData returnData = new ReturnData();
        if ("user".equals(type)) {
            if (state) {
                String sql = "SELECT *from sys_user_permission where sys_permission_id='" + primissionId + "' and sys_user_id='" + id + "'";
                Record record = Db.findFirstByCache("oneDay", MD5.md5(sql), sql);
                if (record != null) {
                    returnData.setCode("000000");
                } else {
                    record = (new Record()).set("sys_user_id", id).set("sys_permission_id", primissionId);
                    boolean save = Db.save("sys_user_permission", record);
                    if (save) {
                        returnData.setCode("000000");
                    } else {
                        returnData.setCode("111111");
                        returnData.setMsg("保存失败");
                    }
                }
            } else {
                String sql = " delete from `sys_user_permission` where sys_user_id ='" + id + "' and sys_permission_id='" + primissionId + "'";
                int del = Db.delete(sql);
                if (del > 0) {
                    returnData.setCode("000000");
                    String sonSql = "SELECT id from sys_permission where parentid='" + primissionId + "'";
                    List<Record> list = Db.find(sonSql);
                    for (int i = 0; i < list.size(); i++) {
                        Record temp = list.get(i);
                        String sonPrimissionId = temp.getStr("id");
                        String delSonSql = " delete from `sys_user_permission` where sys_user_id ='" + id + "' and sys_permission_id='" + sonPrimissionId + "'";
                        int delInt = Db.delete(delSonSql);
                        Syslog.info("删除子权限"+ delInt);
                    }
                } else {
                    returnData.setCode("111111");
                    returnData.setMsg("保存失败");
                }
            }
        } else if (state) {
            String sql = "SELECT *from sys_role_permission where sys_role_id='" + id + "' and sys_permission_id='" + primissionId + "'";
            Record record = Db.findFirstByCache("oneDay", MD5.md5(sql), sql);
            if (record != null) {
                returnData.setCode("000000");
            } else {
                record = (new Record()).set("sys_role_id", id).set("sys_permission_id", primissionId);
                boolean sa = Db.save("sys_role_permission", record);
                if (sa) {
                    returnData.setCode("000000");
                } else {
                    returnData.setCode("111111");
                    returnData.setMsg("保存失败");
                }
            }
        } else {
            String sql = " DELETE from sys_role_permission where sys_role_id='" + id + "' and sys_permission_id='" + primissionId + "'";
            int de = Db.delete(sql);
            if (de > 0) {
                returnData.setCode("000000");
                String sonSql = "SELECT id from sys_permission where parentid='" + primissionId + "'";
                List<Record> list = Db.find(sonSql);
                for (int i = 0; i < list.size(); i++) {
                    Record temp = list.get(i);
                    String sonPrimissionId = temp.getStr("id");
                    String delSonSql = " DELETE from sys_role_permission where sys_role_id='" + id + "' and sys_permission_id='" + sonPrimissionId + "'";
                    Db.delete(delSonSql);
                }
            } else {
                returnData.setCode("111111");
                returnData.setMsg("保存失败");
            }
        }
        return returnData;
    }

    public List<Record> onePermissionService(String userId) {
        List<Record> list = selectPermissionByUserId(userId);
        List<Record> resultList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Record temp = list.get(i);
            String parentid = temp.getStr("parentid");
            if ("0".equals(parentid))
                resultList.add(temp);
        }
        return resultList;
    }

    public List<Record> twoPermissionService(String permissionId, String userId) {
        List<Record> list = selectPermissionByUserId(userId);
        List<Record> resultList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Record temp = list.get(i);
            String parentid = temp.getStr("parentid");
            if (parentid.equals(permissionId))
                resultList.add(temp);
        }
        return resultList;
    }

    public List<Record> threePermissionService(String permissionId, String userId) {
        List<Record> list = selectPermissionByUserId(userId);
        List<Record> resultList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Record temp = list.get(i);
            String parentid = temp.getStr("parentid");
            if (parentid.equals(permissionId)) {
                Syslog.info(temp.toJson());
                resultList.add(temp);
            }
        }
        return resultList;
    }

    public List<Record> selectPermissionByUserId(String userId) {
        String sql = "";
        if ("1".equals(userId)) {
            sql = "SELECT * from sys_permission";
        } else {
            sql = "SELECT spe.id, spe.name,spe.type,spe.url,spe.percode,spe.parentid, spe.parentids,spe.sortstring,  spe.available    from sys_permission   spe LEFT JOIN sys_user_permission sup on spe.id=sup.sys_permission_id \nwhere sup.sys_user_id='" + userId + "'";
            String roleSql = "SELECT spe.id, spe.name,spe.type,spe.url,spe.percode,spe.parentid, spe.parentids,spe.sortstring,  spe.available  from sys_permission spe LEFT JOIN sys_role_permission srp on srp.sys_permission_id=spe.id\nLEFT JOIN sys_role sr on sr.id=srp.sys_role_id LEFT JOIN sys_user_role sur on sur.sys_role_id=sr.id\nWHERE sur.sys_user_id='" + userId + "' GROUP BY spe.id";
            sql = sql + " union " + roleSql;
            sql = " select * from (" + sql + ") rr group by rr. id";
        }
        List<Record> list = Db.find(sql);
        this.cache.setex(userId + "permission", 1800, list);
        return list;
    }

    public ReturnData saveRoleOrUserPermissionService(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        boolean result = true;
        String type = ((String[])map.get("type"))[0];
        String id = ((String[])map.get("id"))[0];
        String ids = ((String[])map.get("ids"))[0];
        String[] idsArr = ids.split(",");
        List<String> idsList = Arrays.asList(idsArr);
        String permissionId = ((String[])map.get("permissionId"))[0];
        if ("role".equals(type)) {
            List<Record> insertList = new ArrayList<>();
            for (int i = 0; i < idsList.size(); i++) {
                String tempId = idsList.get(i);
                Record tempRecord = new Record();
                tempRecord.set("sys_role_id", id);
                tempRecord.set("sys_permission_id", tempId);
                insertList.add(tempRecord);
            }
            String delSql = "DELETE\nFROM\n\tsys_role_permission\nWHERE\n\tsys_role_id = '" + id + "'\n and sys_permission_id in ( SELECT id from sys_permission where parentid='" + permissionId + "' )";
            int delInt = Db.delete(delSql);
            Syslog.info("删除了" + delInt + "数据");
            int[] insertArr = Db.batchSave("sys_role_permission", insertList, insertList.size());
            Syslog.info(insertArr);
            for (int j = 0; j < insertArr.length; j++) {
                if (insertArr[j] == 0)
                    result = false;
            }
        } else if ("user".equals(type)) {
            List<Record> insertList = new ArrayList<>();
            for (int i = 0; i < idsList.size(); i++) {
                String tempId = idsList.get(i);
                Record tempRecord = new Record();
                tempRecord.set("sys_user_id", id);
                tempRecord.set("sys_permission_id", tempId);
                insertList.add(tempRecord);
            }
            String delSql = "DELETE from sys_user_permission where sys_user_id='" + id + "'  and sys_permission_id in ( SELECT id from sys_permission where parentid='" + permissionId + "' ) ";
            int delInt = Db.delete(delSql);
            Syslog.info("删除了" + delInt + "数据");
            int[] insertArr = Db.batchSave("sys_user_permission", insertList, insertList.size());
            Syslog.info(insertArr);
            for (int j = 0; j < insertArr.length; j++) {
                if (insertArr[j] == 0)
                    result = false;
            }
        }
        if (result) {
            returnData.setCode("000000");
            returnData.setMsg("保存成功");
        } else {
            returnData.setCode("111111");
            returnData.setMsg("保存失败");
        }
        return returnData;
    }

    @Before({Tx.class})
    public ReturnData roleDel(Map<String, String[]> map) throws Exception {
        ReturnData data = new ReturnData();
        String rid = ((String[])map.get("rid"))[0];
        String sql0 = "DELETE FROM sys_role where id ='" + rid + "'";
        int aa = Db.delete(sql0);
        String sql = "SELECT COUNT(*) as number FROM sys_role_permission a WHERE a.sys_role_id ='" + rid + "'";
        int num = Db.queryInt(sql).intValue();
        String sql2 = "DELETE FROM sys_role_permission WHERE sys_role_id ='" + rid + "'";
        int ss = Db.delete(sql2);
        if (aa == 1 && num == ss) {
            data.setData("success");
        } else {
            data.setData("false");
        }
        return data;
    }

    public ReturnData findRoleInfo(String rid, String userId) {
        ReturnData data = new ReturnData();
        Map<Object, Object> returnMap = new LinkedHashMap<>();
        List<Record> record1 = new ArrayList<>();
        Map<Object, Object> map1 = new HashMap<>();
        try {
            String sql0 = "SELECT a.`name` FROM sys_role a WHERE a.id='" + rid + "'";
            String roleName = Db.queryStr(sql0);
            map1.put("returnMap", returnMap);
            map1.put("roleName", roleName);
            data.setData(map1);
        } catch (Exception e) {
            Syslog.error("查询角色信息异常"+ e);
        }
        return data;
    }

    public ReturnData updateRole(Map<String, String[]> map) {
        ReturnData data = new ReturnData();
        String rid = ((String[])map.get("rid"))[0];
        String name = ((String[])map.get("name"))[0];
        int ss2 = 0;
        String sql2 = "update sys_role set name='" + name + "' where id='" + rid + "'";
        ss2 = Db.update(sql2);
        if (ss2 == 1) {
            data.setData("success");
            return data;
        }
        data.setData("fail");
        return data;
    }

    public List<Record> getRolesByAdminUserId(String id) {
        String sql = "SELECT  sr.* from sys_role sr where sr.adminUserId='" + id + "' ";
        List<Record> list = Db.find(sql);
        return list;
    }

    public List<Record> getRolesByUserId(String id) {
        String sql = "SELECT sro.* from sys_role sro LEFT JOIN sys_user_role sur on sro.id=sur.sys_role_id where sur.sys_user_id='" + id + "'";
        List<Record> list = Db.find(sql);
        return list;
    }

    public ReturnData saveUserRoleService(Map<String, String[]> map, String adminUserId) throws Exception {
        String id = ((String[])map.get("id"))[0];
        String ids = ((String[])map.get("ids"))[0];
        String[] strArr = ids.split(",");
        ReturnData returnData = new ReturnData();
        boolean result = true;
        List<String> idsList = Arrays.asList(strArr);
        List<Record> nowRoles = getRolesByUserId(adminUserId);
        List<Record> insertList = new ArrayList<>();
        for (int i = 0; i < idsList.size(); i++) {
            String tempId = idsList.get(i);
            Record tempRecord = new Record();
            tempRecord.set("id", UuidUtil.get32UUID());
            tempRecord.set("sys_user_id", id);
            tempRecord.set("sys_role_id", tempId);
            insertList.add(tempRecord);
        }
        String delSql = "DELETE from sys_user_role where sys_user_id='" + id + "'";
        Db.delete(delSql);
        int[] insertArr = Db.batchSave("sys_user_role", insertList, insertList.size());
        for (int j = 0; j < insertArr.length; j++) {
            int k = insertArr[j];
            if (k != 1)
                result = false;
        }
        if (!result) {
            returnData.setCode("111111");
            returnData.setMsg("保存失败");
            throw new Exception();
        }
        returnData.setCode("000000");
        returnData.setMsg("保存成功");
        return returnData;
    }

    public ReturnData userPermissionByUserId(String userId) {
        ReturnData returnData = new ReturnData();
        String permissionSql = "SELECT spi.percode, spi.url,spi.parentid,spi.id,spi.name from sys_permission spi\nLEFT JOIN sys_user_permission sup\non spi.id=sup.sys_permission_id\nLEFT JOIN sys_user su ON\nsup.sys_user_id=su.id\nWHERE su.id='" + userId + "'";
        List<Record> permissionList = Db.find(permissionSql);
        for (int i = 0; i < permissionList.size(); i++) {
            String url = ((Record)permissionList.get(i)).getStr("url");
            int a = url.indexOf("?");
            a = (a == -1) ? url.length() : a;
            url = url.substring(0, a);
            ((Record)permissionList.get(i)).set("url", url);
        }
        returnData.setData(permissionList);
        return returnData;
    }

    public ReturnData departmentPermissionById(String id) {
        ReturnData returnData = new ReturnData();
        String permissionSql = "SELECT spi.percode, spi.url,spi.parentid,spi.id,spi.name from sys_permission spi\nLEFT JOIN sys_user_permission sup\non spi.id=sup.sys_permission_id\nLEFT JOIN sys_user su ON\nsup.sys_user_id=su.id\nWHERE su.id='" + id + "'";
        List<Record> permissionList = Db.find(permissionSql);
        for (int i = 0; i < permissionList.size(); i++) {
            String url = ((Record)permissionList.get(i)).getStr("url");
            int a = url.indexOf("?");
            a = (a == -1) ? url.length() : a;
            url = url.substring(0, a);
            ((Record)permissionList.get(i)).set("url", url);
        }
        returnData.setData(permissionList);
        return returnData;
    }

    public ReturnData authorizationService(ReturnData one, ReturnData two) {
        ReturnData returnData = new ReturnData();
        List<Record> twoList = (List<Record>)two.getData();
        Map<String, List<Record>> oneList = (Map<String, List<Record>>)one.getData();
        for (Map.Entry<String, List<Record>> entry : oneList.entrySet()) {
            List<Record> recordList = entry.getValue();
            for (int i = 0; i < recordList.size(); i++) {
                String url = ((Record)recordList.get(i)).getStr("url");
                int b = url.indexOf("?");
                b = (b == -1) ? url.length() : b;
                url = url.substring(0, b);
                ((Record)recordList.get(i)).set("url", url);
                if (twoList.contains(recordList.get(i)))
                    ((Record)recordList.get(i)).set("checked", "checked");
            }
        }
        returnData.setData(oneList);
        return returnData;
    }

    public String getAdminUserId(String userId) {
        String sql = "SELECT *from sys_user where id='" + userId + "'";
        Record record = Db.findFirstByCache("adminUser", MD5.md5(sql), sql);
        String adminUserId = record.getStr("adminUserId");
        adminUserId = "1".equals(adminUserId) ? record.getStr("id") : adminUserId;
        return adminUserId;
    }

    public ReturnData goOrgNumberEditService(String adminUserId) {
        String sql = "SELECT orgNumber from sys_user where id='" + adminUserId + "'";
        int all = Db.queryInt(sql).intValue();
        String countSql = "SELECT COUNT(*) from yx_org WHERE adminUserId='" + adminUserId + "'";
        int count = Db.queryInt(countSql).intValue();
        ReturnData returnData = new ReturnData();
        Map<Object, Object> map = new HashMap<>();
        map.put("all", Integer.valueOf(all));
        map.put("count", Integer.valueOf(count));
        returnData.setData(map);
        returnData.setMsg("保存成功");
        return returnData;
    }

    public synchronized ReturnData addOrgNumberService(String adminUserId, int addNumber) {
        ReturnData returnData = new ReturnData();
        String sql = "UPDATE sys_user SET orgNumber=orgNumber+" + addNumber + " where id='" + adminUserId + "'";
        int up = Db.update(sql);
        if (up == 1) {
            returnData.setMsg("保存成功");
                    returnData.setCode("000000");
        } else {
            returnData.setMsg("保存失败");
                    returnData.setCode("111111");
        }
        return returnData;
    }

    public Map adminActivityList(Map<String, String[]> parmap) {
        String page = ((String[])parmap.get("page"))[0];
        String limit = ((String[])parmap.get("limit"))[0];
        String activityName = ((String[])parmap.get("activityName"))[0].trim();
        String orgName = ((String[])parmap.get("orgName"))[0].trim();
        String personTel = ((String[])parmap.get("personTel"))[0].trim();
        String sql = "SELECT ya.id, ya.name as activityName ,ya.talkMoney/100 as talkMoney ,ya.createTime,\ncase ya.type\nwhen ya.type=0 then '\nwhen ya.type=1 then '\nELSE '\nend as type,\nyo.name as orgName ,yo.person ,yo.personTel,sus.userCode,sus.userName\n from yx_activity ya LEFT JOIN yx_org yo on ya.orgId=yo.id LEFT JOIN sys_user sus on yo.adminUserId=sus.id\nwhere 1=1 \n";
        if (activityName != "")
            sql = sql + " and ya.name like '%" + activityName + "%' ";
        if (orgName != "")
            sql = sql + " and yo.name like '%" + orgName + "%' ";
        if (personTel != "")
            sql = sql + " and yo.personTel = '" + personTel + "' ";
        sql = sql + " ORDER BY ya.createTime desc ";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql);
        int code = 0;
        String msg ="请求成功";
        int count = pageUtil.getTotalRows();
        Map<Object, Object> map = new HashMap<>();
        map.put("code", Integer.valueOf(code));
        map.put("msg", msg);
        map.put("count", Integer.valueOf(count));
        map.put("data", pageUtil.getList());
        return map;
    }

    public ReturnData saveSystemConfigService(Map<String, String[]> map) {
        boolean sa = false;
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            System.out.println("Key = " + (String)entry.getKey() + ", Value = " + ((String[])entry.getValue())[0]);
            Record record = new Record();
            record.set("settingKey", entry.getKey());
            sa = Db.delete("sys_config", "settingKey", record);
            record.set("settingValue", ((String[])entry.getValue())[0]);
            sa = Db.save("sys_config", "settingKey", record);
            if (!sa) {
                Syslog.error("为保持事务一致性，抛出运行异常");
                throw new RuntimeException();
            }
        }
        ReturnData returnData = new ReturnData(sa);
        return returnData;
    }

    public Record systemConfigService() {
        String sql = "SELECT *from sys_config";
        String key = "systemConfig";
        Record record = new Record();
        Record systemConfig = (Record)this.cache.get(key);
        if (systemConfig == null) {
            List<Record> list = Db.find(sql);
            for (int i = 0; i < list.size(); i++) {
                Record temp = list.get(i);
                record.set(temp.getStr("settingKey"), temp.getStr("settingValue"));
            }
        }
        return record;
    }

    public Map welcomeService(String userId) {
        Map<Object, Object> map = new HashMap<>();
        return map;
    }

    public Record brokenLineService() {
        Record result = new Record();
        try {
            List<String> dateList = new ArrayList<>();
            Date date = new Date();
            List<Record> orderResultList = new ArrayList<>();
            List<Record> memberResultList = new ArrayList<>();
            for (int i = 16; i > 1; i--) {
                Record record = new Record();
                DateFormat df = new SimpleDateFormat("yyyyMMdd");
                String startTime = df.format(Long.valueOf((new Date()).getTime() - (i * 24 * 60 * 60 * 1000)));
                String endTime = df.format(date);
                System.out.println(startTime);
                System.out.println("***************************");
                System.out.println(endTime);
                record.set("dateTime", startTime);
                record.set("number", Integer.valueOf(0));
                orderResultList.add(record);
                memberResultList.add(record);
                dateList.add(startTime);
            }
            result.set("dateList", dateList);
            String startStrDate = ((Record)orderResultList.get(0)).getStr("dateTime");
            String endStrDate = ((Record)orderResultList.get(dateList.size() - 1)).getStr("dateTime");
            String orderSql = " SELECT\n\tDATE_FORMAT(createTime, '%Y%m%d') AS dateTime,COUNT(*) as co\nFROM\n\tshop_order\nWHERE\n\tDATE_FORMAT(createTime, '%Y%m%d')\nBETWEEN '" + startStrDate + "' AND '" + endStrDate + "'  GROUP BY   DATE_FORMAT(createTime, '%Y%m%d') ";
            List<Record> orderList = Db.find(orderSql);
            for (int j = 0; j < orderResultList.size(); j++) {
                Record dateRecord = orderResultList.get(j);
                String dateTime = dateRecord.getStr("dateTime");
                for (int m = 0; m < orderList.size(); m++) {
                    Record order = orderList.get(m);
                    String orderDateTime = order.getStr("dateTime");
                    if (dateTime.equals(orderDateTime))
                        dateRecord.set("number", order.getStr("co"));
                }
                orderResultList.set(j, dateRecord);
            }
            result.set("orderList", orderResultList);
            String memberSql = " SELECT\n\tDATE_FORMAT(createTime, '%Y%m%d') AS dateTime,COUNT(*) as co\nFROM\n\tyx_member\nWHERE\n\tDATE_FORMAT(createTime, '%Y%m%d')\nBETWEEN '" + startStrDate + "' AND '" + endStrDate + "'  GROUP BY   DATE_FORMAT(createTime, '%Y%m%d') ";
            List<Record> memberList = Db.find(memberSql);
            for (int k = 0; k < memberResultList.size(); k++) {
                Record dateRecord = memberResultList.get(k);
                String dateTime = dateRecord.getStr("dateTime");
                for (int m = 0; m < memberList.size(); m++) {
                    Record member = memberList.get(m);
                    String memberDateTime = member.getStr("dateTime");
                    if (dateTime.equals(memberDateTime))
                        dateRecord.set("number", member.getStr("co"));
                }
                memberResultList.set(k, dateRecord);
            }
            result.set("memberList", memberResultList);
        } catch (Exception e) {
            Syslog.error(e);
        }
        return result;
    }

    public List yearStatistics() {
        try {
            List<Record> orderList = new ArrayList<>();
            for (int i = 1; i < 13; i++) {
                String strYear = DateUtil.getSdfTimes().substring(2, 4);
                if (i < 10) {
                    strYear = strYear + "0" + i;
                } else {
                    strYear = strYear + i;
                }
                Record record = (new Record()).set("month", strYear).set("number", Integer.valueOf(0));
                orderList.add(record);
            }
            String sql = "SELECT\n\tDATE_FORMAT(createTime, '%y%m') AS dateTime ,COUNT(*) as co\nFROM\n\tshop_order\nWHERE\n\tDATE_FORMAT(createTime, '%Y')= DATE_FORMAT(createTime, '%Y')\n  GROUP BY  DATE_FORMAT(createTime, '%m')";
            List<Record> dbList = Db.find(sql);
            for (int j = 0; j < orderList.size(); j++) {
                Record record = orderList.get(j);
                String month = record.getStr("month");
                for (int k = 0; k < dbList.size(); k++) {
                    Record temp = dbList.get(k);
                    if (month.equals(temp.getStr("dateTime")))
                        record.set("month", month).set("number", temp.getStr("co"));
                }
                orderList.set(j, record);
            }
            return orderList;
        } catch (Exception e) {
            Syslog.error(e);
            return null;
        }
    }

    public List<Record> commodityOrderStatistics() {
        String sql = "SELECT SUM(number) as number, commodityName from shop_order_info  GROUP BY commodityId";
        List<Record> list = Db.find(sql);
        return list;
    }
}
